import React from "react";
class UserInput extends React.Component {
  state = {
    user: this.props.user,
  };

  handleChange = (e) => {
    console.log("onchange", e.target.value);
    console.log("state", this.state);
    let newState = {
      user: {
        ...this.state.user,
        name: e.target.value,
      },
    };
    console.log("newState", newState);
    this.props.onChange(e.target.value);
    // this.setState(
    //   {
    //     user: {
    //       ...this.state.user,
    //       name: e.target.value,
    //     },
    //   },
    //   () => {
    //     console.log("setState以后的", this.state);
    //   }
    // );
  };
  static getDerivedStateFromProps(props, state) {
    console.log("getDerivedStateFromProps");
    return {
      user: props.user,
    };
  }

  render() {
    const { onConfirm } = this.props;
    const { user } = this.state;
    return (
      <div>
        <input value={user.name || ""} onChange={this.handleChange} />
        <button
          onClick={() => {
            onConfirm(user);
          }}
        >
          确定
        </button>
      </div>
    );
  }
}

class App extends React.Component {
  state = {
    users: [
      { id: 0, name: "bruce" },
      { id: 1, name: "frank" },
      { id: 2, name: "tony" },
    ],
    targetUser: {},
  };

  onConfirm = (user) => {
    const { users } = this.state;
    const target = users.find((u) => u.id === user.id);

    if (target) {
      this.setState({
        users: [
          ...users.slice(0, users.indexOf(target)),
          user,
          ...users.slice(users.indexOf(target) + 1),
        ],
      });
    } else {
      const id = Math.max(...users.map((u) => u.id)) + 1;
      this.setState({
        users: [
          ...users,
          {
            ...user,
            id,
          },
        ],
      });
    }
  };
  onChange = (value) => {
    this.setState({
      targetUser: {
        ...this.state.targetUser,
        name: value,
      },
    });
  };
  render() {
    const { users, targetUser } = this.state;
    return (
      <div>
        <UserInput
          user={targetUser}
          onConfirm={this.onConfirm}
          onChange={this.onChange}
        />
        <ul>
          {users.map((u) => (
            <li key={u.id}>
              {u.name}
              <button
                onClick={() => {
                  this.setState({ targetUser: u });
                }}
              >
                编辑
              </button>
            </li>
          ))}
        </ul>
        <button
          onClick={() => {
            this.setState({ targetUser: {} });
          }}
        >
          新建
        </button>
      </div>
    );
  }
}

// ReactDOM.render(<App />, document.getElementById("root"));

export default App;
